import React, { useState, useEffect, useRef } from 'react';
import { FormField } from 'types/Form.d';
import { Form, Row, Col, FormInstanceFunctions, Input, Radio, Select, DateRangePicker, Textarea, DatePicker, Upload, message, InputNumber, InputAdornment } from 'tdesign-react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import proxy from '../../configs/host';
import './index.module.less';
import { uploadFileApi } from 'api/common';

export type DrawerFormField = {
  name: string;
  label: string;
  labelWidth?: number;
  type: 'input' | 'select' | 'radio' | 'date' | 'dateRange' | 'textarea' | 'upload' | 'richEditor' | 'inputNumber' | 's-input' | 'render';
  options?: Array<{ label: string; value: any }>;
  required?: boolean;
  max?: number;
  rules?: any[];
  requiredMessage?: string;
  disabled?: boolean;
  placeholder?: string;
  help?: string;
  props?: any;
  formItemStyle?: React.CSSProperties;
  textareaProps?: {
    maxLength?: number;
    tips?: string;
  };
  colSpan?: number; 
  inputWidth?: string | number; 
  minInputWidth?: string | number;
  onChange?: (value: any, form?: any) => void;
  defaultValue?: any;
  colWrap?: {
    labelWidth?: number;
  };
  appendSuffix?: string; // 新增：输入框后缀
  visible?: (formValues: any) => boolean; // 新增：条件显示字段
  // s-input 类型特有配置
  sInputConfig?: {
    inputName: string; 
    selectName: string; // 选择框字段名
    selectOptions: Array<{ label: string; value: any }>; 
    inputPlaceholder?: string; // 输入框占位符
    selectPlaceholder?: string; // 选择框占位符
    inputProps?: any; // 输入框额外属性
    selectProps?: any; // 选择框额外属性
    callback?: (value: any) => void; // 选择变化回调
  };
  onBlur?: (value: any) => void;
  // render 类型特有配置
  render?: (form: any, field: DrawerFormField) => React.ReactNode;
};

interface DrawerFormProps {
  fields: DrawerFormField[];
  form?: any;
  formRef?: React.RefObject<FormInstanceFunctions>;
  labelWidth?: number;
  inputWidth?: string | number; // 新增：input宽度配置
  minInputWidth?: string | number; // 新增：input最小宽度
  gutter?: [number, number];
  rowStyle?: React.CSSProperties;
  gutterStyle?: React.CSSProperties;
  onFieldChange?: (name: string, value: any) => void;
  uploadApi?: (formData: FormData) => Promise<any>; // 新增：上传接口
  onUploadSuccess?: (url: string, fieldName: string) => void; // 新增：上传成功回调
}

const { FormItem } = Form;

const DrawerForm: React.FC<DrawerFormProps> = ({
  fields,
  form,
  formRef,
  labelWidth = 120,
  inputWidth = '100%',
  minInputWidth = '200px',
  gutter = [16, 16],
  rowStyle,
  gutterStyle,
  onFieldChange,
  uploadApi,
  onUploadSuccess,
}) => {
  const quillRefs = useRef<Record<string, any>>({});
  const [formValues, setFormValues] = useState<any>({});

  // 监听表单值变化，用于更新字段可见性
  useEffect(() => {
    if (form) {
      const currentValues = form.getFieldsValue();
      setFormValues(currentValues);
    }
  }, [form]);

  // 通用的字段值变化处理函数
  const handleFieldChange = (field: DrawerFormField, value: any) => {
    if (field.onChange) {
      field.onChange(value, form);
    }
    if (onFieldChange) {
      onFieldChange(field.name, value);
    }
    
    // 直接更新表单值状态以触发字段重新渲染
    setFormValues((prevValues: any) => {
      const newValues = {
        ...prevValues,
        [field.name]: value
      };
      return newValues;
    });
  };
  

  const getInputStyle = (field: DrawerFormField) => {
    const fieldWidth = field.inputWidth || inputWidth;
    return {
      width: fieldWidth,
      minWidth: field.minInputWidth || minInputWidth,
    };
  };

  const buildQuillModules = (fieldName: string) => {
    return {
      toolbar: {
        container: [
          [{ header: [1, 2, 3, 4, 5, 6, false] }],
          ['bold', 'italic', 'underline', 'strike'],
          [{ color: [] }, { background: [] }],
          [{ list: 'ordered' }, { list: 'bullet' }],
          [{ indent: '-1' }, { indent: '+1' }],
          [{ align: [] }],
          ['link', 'image'],
          ['clean'],
        ],
        handlers: {
          image: async () => {
            const editor = quillRefs.current[fieldName]?.getEditor?.();
            if (!editor) return;
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.onchange = async () => {
              const file = (input.files && input.files[0]) || null;
              if (!file) return;
              try {
                const formData = new FormData();
                formData.append('file', file);
                // 使用传入的 uploadApi，否则回退到通用 API
                let resp: any = undefined;
                if (uploadApi) {
                  resp = await uploadApi(formData);
                } else {
                  resp = await uploadFileApi(formData);
                }
                const env = (import.meta.env.MODE || 'development') as keyof typeof proxy;
                const API_HOST = proxy[env]?.API || proxy.development.API;
                const fileUrl = resp?.url || resp?.data?.url || resp?.file_upload || resp?.data?.file_upload;
                const finalUrl = fileUrl ? (fileUrl.startsWith('http') ? fileUrl : `${API_HOST}/${fileUrl}`) : '';
                if (finalUrl) {
                  const range = editor.getSelection(true);
                  editor.insertEmbed(range ? range.index : 0, 'image', finalUrl, 'user');
                  editor.setSelection((range ? range.index : 0) + 1);
                  onUploadSuccess?.(finalUrl, fieldName);
                } else {
                  message.error('上传失败：未返回图片地址');
                }
              } catch (e) {
                message.error('上传失败，请重试');
              }
            };
            input.click();
          },
        },
      },
    };
  };

  const renderFormItem = (field: DrawerFormField) => {
    const inputStyle = getInputStyle(field);
    
    switch (field.type) {
      case 'select':
        return (
          <Select
            options={field.options || []}
            placeholder={field.placeholder || '请选择'}
            clearable
            disabled={field.disabled}
            style={inputStyle}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
          />  
        );
        case 's-input':
          if (!field.sInputConfig) {
            console.warn('s-input type requires sInputConfig');
            return null;
          }
          
          const { inputName: rawInputName, selectOptions, selectPlaceholder, inputProps, selectProps ,callback} = field.sInputConfig;
          const inputName = rawInputName || field.name;
          const inputValue = formValues[inputName] ?? formValues[field.name] ?? '';
          
          // 获取第一个选项的值作为默认值
          const defaultSelectValue = selectOptions && selectOptions.length > 0 ? selectOptions[0].value : '';
          
          return (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' ,...inputStyle}}>
              <Input
                placeholder={field.placeholder || '请输入'}
                disabled={field.disabled}
                value={String(inputValue ?? '')}
                clearable
                maxlength={field.max}
                style={{ ...inputStyle,flex: 1 }}
                onChange={(value) => {
                  const next = String(value).replace(/[^0-9]/g, '');
                  
                  // 获取当前选择框的值来判断限制范围
                  const selectValue = formValues[field.sInputConfig?.selectName || ''] || defaultSelectValue;
                  const isDay = selectValue === 'day';
                  const maxValue = isDay ? 30 : 23;
                  const minValue = 1;
                  
                  // 如果输入为空，允许清空
                  if (next === '') {
                    form?.setFieldsValue?.({ [inputName]: next, [field.name]: next });
                    setFormValues((prev: any) => ({ ...prev, [inputName]: next, [field.name]: next }));
                    handleFieldChange(field, next);
                    return;
                  }
                  
                  // 转换为数字进行范围检查
                  const numValue = parseInt(next, 10);
                  if (numValue >= minValue && numValue <= maxValue) {
                    form?.setFieldsValue?.({ [inputName]: next, [field.name]: next });
                    setFormValues((prev: any) => ({ ...prev, [inputName]: next, [field.name]: next }));
                    handleFieldChange(field, next);
                  } else if (numValue > maxValue) {
                    // 如果超出最大值，设置为最大值
                    const validValue = String(maxValue);
                    form?.setFieldsValue?.({ [inputName]: validValue, [field.name]: validValue });
                    setFormValues((prev: any) => ({ ...prev, [inputName]: validValue, [field.name]: validValue }));
                    handleFieldChange(field, validValue);
                  } else if (numValue < minValue) {
                    return;
                  }
                }}
                {...(inputProps || {})}
              />
                <Select
                  value={formValues[field.sInputConfig?.selectName || ''] || defaultSelectValue}
                  options={selectOptions}
                  placeholder={selectPlaceholder || '请选择'}
                  disabled={field.disabled}
                  style={{ ...inputStyle,width: '120px' }}
                  onChange={(value) => {
                    // 更新选择框的值到表单状态
                    const selectFieldName = field.sInputConfig?.selectName || '';
                    if (selectFieldName) {
                      form?.setFieldsValue?.({ [selectFieldName]: value });
                      setFormValues((prev: any) => ({ ...prev, [selectFieldName]: value }));
                    }
                    
                    callback?.(value);
                    
                    // 当选择框值改变时，重新验证输入框的值
                    const currentInputValue = formValues[inputName] ?? formValues[field.name] ?? '';
                    if (currentInputValue) {
                      const isDay = value === 'day';
                      const maxValue = isDay ? 30 : 23;
                      const numValue = parseInt(String(currentInputValue), 10);
                      
                      if (numValue > maxValue) {
                        const validValue = String(maxValue);
                        form?.setFieldsValue?.({ [inputName]: validValue, [field.name]: validValue });
                        setFormValues((prev: any) => ({ ...prev, [inputName]: validValue, [field.name]: validValue }));
                        handleFieldChange(field, validValue);
                      }
                    }
                  }}
                  {...selectProps}
                />
              </div>
          );
      case 'input':
        if(field.appendSuffix){
          return (
            <InputAdornment append={field.appendSuffix} style={inputStyle}>
              <Input
                placeholder={field.placeholder || '请输入'}
                clearable
                disabled={field.disabled}
                style={inputStyle}
                {...field.props}
              />
            </InputAdornment>
          );
        }
        return (
          <Input
            placeholder={field.placeholder || '请输入'}
            clearable
            disabled={field.disabled}
            style={inputStyle}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
            onBlur={()=>{
              field.onBlur?.(formValues[field.name]);
            }}
            {...field.props}
          />
        );
      case 'textarea':
        return (
          <Textarea
            placeholder={field.placeholder || '请输入'}
            disabled={field.disabled}
            maxcharacter={field.textareaProps?.maxLength}
            tips={field.textareaProps?.tips}
            style={inputStyle}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
            {...field.props}
          />
        );
      case 'radio':
        return (
          <Radio.Group
            style={inputStyle}
            value={(typeof (form?.getFieldValue?.(field.name)) === 'string') ? Number(form?.getFieldValue?.(field.name)) : form?.getFieldValue?.(field.name)}
            onChange={(value) => {
              const next = (typeof value === 'string') ? Number(value) : value;
              handleFieldChange(field, next);
            }}
          >
            {(field.options || []).map((item) => (
              <Radio key={item.value} value={item.value} disabled={field.disabled}>
                {item.label}
              </Radio>
            ))}
          </Radio.Group>
        );
      case 'date':
        return (
          <DatePicker
            placeholder={field.placeholder || '请选择日期'}
            clearable
            disabled={field.disabled}
            style={inputStyle}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
          />
        );
      case 'dateRange':
        return (
          <DateRangePicker
            placeholder={field.placeholder || ['开始时间', '结束时间']}
            clearable
            disabled={field.disabled}
            style={inputStyle}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
          />
        );
      case 'inputNumber':
        if(field.appendSuffix){
          return (
            <InputAdornment append={field.appendSuffix} style={inputStyle}>
              <InputNumber
              theme="normal"
                placeholder={field.placeholder || '请输入'}
                disabled={field.disabled}
                style={inputStyle}
                {...field.props}
              />
            </InputAdornment>
          );
        }
        return (
          <InputNumber
            placeholder={field.placeholder || '请输入'}
            disabled={field.disabled}
            style={inputStyle}
            {
              ...field.props
            }
          />
        );
      case 'upload':
        return (
          <Upload
            theme="image"
            placeholder={field.placeholder || '请选择图片'}
            disabled={field.disabled}
            style={inputStyle}
            value={form?.getFieldValue?.(field.name) || []}
            showName={false}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
            requestMethod={uploadApi ? async (file: any) => {
              try {
                const formData = new FormData();
                const fileToUpload = file.raw || file;
                formData.append('file', fileToUpload);
                const response = await uploadApi(formData);
                const env = (import.meta.env.MODE || 'development') as keyof typeof proxy;
                const API_HOST = proxy[env]?.API || proxy.development.API;
                const fileUrl = response.file_upload || response.data?.file_upload;
                const fullImageUrl = `${API_HOST}/${fileUrl}`;
                message.success('上传成功');
                const result = {
                  url: fullImageUrl,
                  name: '',
                  status: 'success',
                };
                if (onUploadSuccess) {
                  onUploadSuccess('/'+fileUrl, field.name);
                }
                
                return result;
              } catch (error) {
                console.error('上传失败:', error);
                message.error('上传失败，请重试');
                return {
                  url: '',
                  name: '',
                  status: 'fail',
                };
              }
            } : undefined}
            {...field.props}
          />
        );
      case 'richEditor':
        const quillModules = React.useMemo(() => buildQuillModules(field.name), [field.name, uploadApi]);
        return (
          <ReactQuill
            ref={(el) => { if (el) quillRefs.current[field.name] = el; }}
            theme="snow"
            className="drawer-form-quill"
            value={(() => { const v = form?.getFieldValue?.(field.name); return typeof v === 'string' ? v : (v != null ? String(v) : ''); })()}
            onChange={(value) => {
              handleFieldChange(field, value);
            }}
            style={{ width: '100%', minHeight: '200px', ...(inputStyle as any) }}
            modules={quillModules}
            {...field.props}
          />
        );
      case 'render':
        if (!field.render) {
          console.warn('render type requires render function');
          return <span>请提供 render 函数</span>;
        }
        return field.render(form, field);
      default:
        return <span>请设置组件类型type</span>;
    }
  };

  const getColSpan = (field: DrawerFormField) => {
    if (field.colSpan) {
      return field.colSpan;
    }
    
    // 固定为两列布局，每列占12个栅格
    return 12;
  };

  // 将字段按行分组，考虑colSpan
  const groupFieldsIntoRows = (fields: DrawerFormField[]) => {
    const rows = [];
    let currentRow = [];
    
    for (let i = 0; i < fields.length; i++) {
      const field = fields[i];
      const fieldSpan = getColSpan(field);
      
      // 如果字段占满整行(24)，先结束当前行
      if (fieldSpan === 24) {
        if (currentRow.length > 0) {
          rows.push(currentRow);
          currentRow = [];
        }
        // 将占满整行的字段单独成行
        rows.push([field]);
        continue;
      }
      
      // 如果当前行已经有2个字段，开始新行
      if (currentRow.length >= 2) {
        rows.push(currentRow);
        currentRow = [];
      }
      
      currentRow.push(field);
    }
    
    // 添加最后一行
    if (currentRow.length > 0) {
      rows.push(currentRow);
    }
    
    return rows;
  };

  // 过滤可见字段
  const visibleFields = fields.filter(field => {
    if (field.visible && typeof field.visible === 'function') {
      try {
        return field.visible(formValues);
      } catch (error) {
        console.warn('Error in field visible function:', error);
        return true;
      }
    }
    return true;
  });

  const fieldRows = groupFieldsIntoRows(visibleFields);
  
  return (
    <div className="drawer-form-container">
      <Form 
        form={form} 
        ref={formRef} 
        labelWidth={labelWidth} 
        colon
      >
        {fieldRows.map((rowFields, rowIndex) => (
          <Row 
            key={rowIndex}
            style={{ 
              marginBottom: '20px', 
              width: '100%', 
              ...rowStyle 
            }} 
            gutter={gutter}
          >
            {rowFields.map((field, colIndex) => (
              <Col key={`${rowIndex}-${colIndex}`} span={getColSpan(field)}>
                <FormItem
                  label={field.label}
                  name={field.name}
                  labelWidth={field.colWrap?.labelWidth !== undefined ? field.colWrap?.labelWidth : labelWidth}
                  help={field.help && <span style={{ color: '#7868e6' }}>{field.help}</span>}
                  rules={
                    (field.rules && field.rules.length > 0)
                      ? field.rules.map(rule => ({ ...rule, trigger: 'blur' }))
                      : (field.required ? [{ required: true, message: field.requiredMessage || `${field.label}是必填项`, trigger: 'blur' }] : [])
                  }
                  style={{ ...field.formItemStyle }}
                >
                  {renderFormItem(field)}
                </FormItem>
              </Col>
            ))}
          </Row>
        ))}
      </Form>
    </div>
  );
};

export default DrawerForm;
